package service.impl;

import common.MyOrder;
import common.OrderFoodUtil;
import common.OrderItem;
import mapper.*;
import org.springframework.stereotype.Service;
import pojo.*;
import service.IMainService;
import service.IOrderService;

import javax.annotation.Resource;
import java.util.*;

@Service("orderService")
public class OrderServiceImpl implements IOrderService {
    @Resource
    private HeiZaiOrderMapper heiZaiOrderMapper;

    @Resource
    private OrderFoodMapper orderFoodMapper;

    @Resource
    private RestaurantMapper restaurantMapper;

    @Resource
    private FoodMapper foodMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private IMainService mainService;

    @Override
    public User newOrder(OrderItem orderItem) {
        // 注意事务
        // 用户扣款
        User user = new User();
        user.setId(orderItem.getUid());
        user.setWallet(orderItem.getTotal());

        int userResult = userMapper.updateWalletById(user);
        if (userResult < 1) {
            return null;
        }

        // 创建订单
        HeiZaiOrder heiZaiOrder = new HeiZaiOrder();
        String orderId = UUID.randomUUID().toString();
        heiZaiOrder.setOrderId(orderId);
        heiZaiOrder.setUserId(orderItem.getUid());
        heiZaiOrder.setRestaurantId(orderItem.getRid());
        heiZaiOrder.setOrderRemark(orderItem.getRemark());
        heiZaiOrder.setBoxCost(orderItem.getBoxCost());
        heiZaiOrder.setTotalMoney(orderItem.getTotal());
        heiZaiOrder.setUserAddId(orderItem.getAddressId());
        // 设置已付款状态
        heiZaiOrder.setSta((byte) 1);
        heiZaiOrder.setCreateTime(new Date());
        int orderResult = heiZaiOrderMapper.insertSelective(heiZaiOrder);

        // 获得创建订单的id
        HeiZaiOrder order1 = heiZaiOrderMapper.selectByOrderId(orderId);

        if (order1 == null) {
            return null;
        } else {
            // 订单创建成功, 创建订单餐品相关表
            for (OrderFoodUtil foodUtil : orderItem.getFoodList()) {

                OrderFood orderFood = new OrderFood();
                orderFood.setOrderId(order1.getId());
                orderFood.setRestaurantId(orderItem.getRid());
                orderFood.setFoodId(foodUtil.getId());
                orderFood.setNumber(foodUtil.getCount());
                orderFood.setPrice(foodUtil.getPrice());

                int orderFoodResult = orderFoodMapper.insertSelective(orderFood);
                if (orderFoodResult < 1) {
                    return null;
                }

                // 修改餐品销量
                Food food = new Food();
                food.setId(foodUtil.getId());
                food.setTotalSales(Short.valueOf(foodUtil.getCount().toString()));
                int updateSales = foodMapper.updateSalesById(food);
                if (updateSales < 1) {
                    return null;
                }
            }

        }
        user = mainService.getUserById(orderItem.getUid());
        return user;
    }

    @Override
    public List<MyOrder> myOrder(Integer uid) {
        // 我的订单列表
        List<MyOrder> list = new ArrayList<>();
        // 根据用户id查询到的order记录列表
        List<HeiZaiOrder> myOrderList = heiZaiOrderMapper.selectByUserId(uid);

        return getMyOrder(myOrderList);
    }

    @Override
    public List<MyOrder> latestOrder(Map<String, Object> map) {

        List<HeiZaiOrder> latestOrderList = heiZaiOrderMapper.selectLatestByRestaurantId(map);
        return getMyOrder(latestOrderList);
    }

    @Override
    public List<MyOrder> completedOrder(  Map<String, Object> map ) {
        List<HeiZaiOrder> completedOrderList = heiZaiOrderMapper.selectCompletedByRestaurantId(map);

        return getMyOrder(completedOrderList);
    }

    /**
     * 得到想要展示的订单信息列表
     *
     * @param hzOrderList 数据库查出的原始数据
     * @return 订单信息列表
     */
    private List<MyOrder> getMyOrder(List<HeiZaiOrder> hzOrderList) {
        List<MyOrder> list = new ArrayList<>();
        for (HeiZaiOrder order : hzOrderList) {
            MyOrder myOrder = new MyOrder();

            myOrder.setId(order.getId());
            myOrder.setRestaurantId(order.getRestaurantId());
            myOrder.setOrderId(order.getOrderId());

            Restaurant restaurant = restaurantMapper.selectByPrimaryKey(order.getRestaurantId());
            myOrder.setRestaurantName(restaurant.getRestaurantName());
            myOrder.setRestaurantImg(restaurant.getRestaurantImg());
            List<OrderFood> orderFoodList = orderFoodMapper.selectByOrderId(order.getId());

            myOrder.setOrderFoods(getOrderFoodUtilList(orderFoodList));
            Address address = addressMapper.selectByPrimaryKey(order.getUserAddId());
            myOrder.setAddress(address.getAddress() + " ," + address.getName());
            myOrder.setSta(order.getSta());
            myOrder.setBoxCost(restaurant.getBoxCost());
            myOrder.setTotalMoney(order.getTotalMoney());
            list.add(myOrder);
        }
        return list;
    }

    // 返回需要展示的订单食物
    private OrderFoodUtil[] getOrderFoodUtilList(List<OrderFood> orderFoodList) {
        OrderFoodUtil[] orderFoodUtils = new OrderFoodUtil[orderFoodList.size()];

        OrderFood orderFood;
        Food food;
        for (int i = 0; i < orderFoodList.size(); i++) {
            OrderFoodUtil ofUtil = new OrderFoodUtil();
            orderFood = orderFoodList.get(i);
            food = foodMapper.selectByPrimaryKey(orderFood.getFoodId());
            ofUtil.setId(food.getId());
            ofUtil.setTitle(food.getTitle());
            ofUtil.setCount(orderFood.getNumber());
            ofUtil.setPrice(orderFood.getPrice());
            ofUtil.setCover(orderFood.getCover());
            orderFoodUtils[i] = ofUtil;
        }

        return orderFoodUtils;
    }

    @Override
    public int receiveOrder(Integer id) {
        HeiZaiOrder order = new HeiZaiOrder();
        order.setId(id);
        order.setSta((byte) 2);
        return heiZaiOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public int send(Integer id) {
        HeiZaiOrder order = new HeiZaiOrder();
        order.setId(id);
        order.setSta((byte) 3);
        return heiZaiOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public int confirm(Integer id) {
        HeiZaiOrder order = heiZaiOrderMapper.selectById(id);
        order.setSta((byte) 4);
        //修改订单状态
        int res1 = heiZaiOrderMapper.updateByPrimaryKeySelective(order);


        //修改用户金额
        Map<String, Object> userMap = new HashMap<>();
        int userId = heiZaiOrderMapper.selectUserIdById(id);
        userMap.put("id", userId);
        userMap.put("wallet", order.getTotalMoney());
        int res2 = userMapper.updateBusinessWalletById(userMap);

        //修改餐厅金额
        Map<String, Object> restaurantMap = new HashMap<>();
        restaurantMap.put("id", order.getRestaurantId());
        restaurantMap.put("money", order.getTotalMoney());
        int res3 = restaurantMapper.updateMoneyById(restaurantMap);

        if (res1 > 0 && res2 > 0 && res3 > 0) return res3;


        return 0;
    }

    @Override
    public int comment(Comment comment) {
        int result1 = commentMapper.insertSelective(comment);
        HeiZaiOrder heiZaiOrder = heiZaiOrderMapper.selectByPrimaryKey(comment.getOrderId());
        heiZaiOrder.setSta((byte) 0);
        if (result1 > 0) {
            return heiZaiOrderMapper.updateByPrimaryKey(heiZaiOrder);
        }
        return 0;
    }

    @Override
    public Comment myComment(Integer id) {
        return commentMapper.selectByOrderId(id);
    }

    @Override
    public int selectTotal(Map<String, Object> map) {
        return heiZaiOrderMapper.selectTotal(map);
    }

    @Override
    public int selectCompletedTotal(Map<String, Object> map) {
        return heiZaiOrderMapper.selectCompletedTotal(map);
    }
}
